<template>
  <div>
    <v-card class="pa-3">
      <h3>评论区</h3>
      <v-form @submit.prevent="send">
        <v-text-field
          label="发表评论"
          append-icon="mdi-send"
          v-model="content"
          @click:append="send"
        ></v-text-field>
      </v-form>
      <div>
        <v-list v-if="comments.length">
          <v-list-item v-for="item of comments" :key="item._id">
            <v-list-item-avatar color="primary" class="white--text">
              <v-img v-if="item.user.avatar" :src="item.user.avatar"></v-img>
              <span v-else>{{ item.user.username[0].toUpperCase() }}</span>
            </v-list-item-avatar>
            <v-list-item-content>
              <v-list-item-title>{{ item.content }}</v-list-item-title>
              <v-list-item-subtitle>
                <span>{{ item.user.username }}</span>
                <span>{{
                    dayjs(item.createdAt).format('YYYY-MM-DD hh:mm:ss')
                  }}</span>
              </v-list-item-subtitle>
            </v-list-item-content>
          </v-list-item>
        </v-list>
        <div v-else>暂无评论</div>
      </div>
    </v-card>
  </div>
</template>

<script>
import * as dayjs from 'dayjs'
export default {
  data() {
    return {
      dayjs,
      content: '',
      comments: [],
    }
  },
  props: {
    type: {
      type: String,
      required: true,
    },
    object: {
      type: String,
      required: true,
    },
  },
  methods: {
    async send() {
      const res = await this.$axios
        .post('comments', {
          type: this.type,
          object: this.object,
          content: this.content,
        })
        .catch((err) => {
          this.$message.error(err.message)
          this.$router.push('/registry')
        })
      if (res) {
        this.content = ''
        this.fetch()
      }
    },

    async fetch() {
      const res = await this.$axios.$get('comments', {
        params: {
          query: {
            where: {
              type: this.type,
              object: this.object,
            },
          },
        },
      })
      this.comments = res.data
    },
  },
  watch: {
    object: {
      handler: 'fetch',
      immediate: true,
    },
  },
}
</script>

<style scoped lang="scss"></style>
